Coverage Report

Created: 2026-11-19 22:35

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
D:\a\cssh-rs\cssh-rs\cssh-rs-core\src\daemon\mod.rs
Line
Count
Source
1
//! Daemon implementation
2
3
#![deny(clippy::implicit_return)]
4
#![allow(clippy::needless_return, clippy::doc_overindented_list_items)]
5
#![warn(missing_docs)]
6
7
use std::collections::HashMap;
8
use std::{
9
    io,
10
    sync::{Arc, Mutex},
11
    time::Duration,
12
};
13
use std::{thread, time};
14
15
use crate::get_console_window_handle;
16
use crate::utils::config::{Cluster, DaemonConfig, EdgeBehavior};
17
use crate::utils::windows::{clear_screen, set_console_color, WindowsApi};
18
use cssh_rs_meta::PACKAGE_NAME;
19
20
use crate::{
21
    current_exe_path, spawn_console_process,
22
    utils::windows::{
23
        arrange_console, control_endpoint, get_console_input_buffer, read_keyboard_input,
24
        set_console_border_color, WindowsControlChannelServer,
25
    },
26
    WindowsSettingsDefaultTerminalApplicationGuard,
27
};
28
use bracoxide::explode;
29
use cssh_rs_platform::ControlChannelServer;
30
use cssh_rs_protocol::v1::capability::{check_version, negotiate_max_frame_len};
31
use cssh_rs_protocol::v1::codec::{decode_frames, encode_frame};
32
use cssh_rs_protocol::v1::handshake::{Hello, Welcome};
33
use cssh_rs_protocol::v1::input::ClientRunState;
34
use cssh_rs_protocol::v1::limits::DEFAULT_MAX_FRAME_LEN;
35
use cssh_rs_protocol::v1::message::DaemonToClient;
36
use cssh_rs_protocol::v1::version::{ProtocolVersion, Role};
37
use cssh_rs_protocol::ClientState;
38
use log::{debug, error, warn};
39
use tokio::{
40
    sync::{
41
        broadcast::{self, error::RecvError, Receiver, Sender},
42
        watch,
43
    },
44
    task::JoinHandle,
45
};
46
use windows::Win32::System::Console::{
47
    CONSOLE_CHARACTER_ATTRIBUTES, INPUT_RECORD_0, KEY_EVENT_RECORD, LEFT_ALT_PRESSED,
48
    LEFT_CTRL_PRESSED, RIGHT_ALT_PRESSED, RIGHT_CTRL_PRESSED, SHIFT_PRESSED,
49
};
50
51
use windows::Win32::UI::Input::KeyboardAndMouse::{
52
    VIRTUAL_KEY, VK_A, VK_C, VK_D, VK_DOWN, VK_E, VK_ESCAPE, VK_H, VK_J, VK_K, VK_L, VK_LEFT, VK_N,
53
    VK_R, VK_RIGHT, VK_T, VK_UP,
54
};
55
use windows::Win32::UI::WindowsAndMessaging::{SW_RESTORE, SW_SHOWMINIMIZED, SW_SHOWNOACTIVATE};
56
use windows::Win32::{
57
    Foundation::{COLORREF, HANDLE, HWND, STILL_ACTIVE},
58
    System::{Console::ENABLE_PROCESSED_INPUT, Threading::PROCESS_QUERY_INFORMATION},
59
};
60
61
use self::grid::{grid_dimensions, ClientGrid};
62
use self::workspace::WorkspaceArea;
63
64
mod grid;
65
mod input;
66
mod workspace;
67
68
/// The capacity of the broadcast channel used
69
/// to send the input records read from the console input buffer
70
/// to the named pipe servers connected to each client in parallel.
71
const SENDER_CAPACITY: usize = 1024 * 1024;
72
73
const DAEMON_PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(1, 0);
74
75
/// A frame encoded once and fanned out to every client's pipe-server task.
76
#[derive(Clone, Debug)]
77
enum ClientBroadcast {
78
    /// Dropped by disabled clients.
79
    Keystroke(Arc<[u8]>),
80
    /// Delivered to every client, which then disconnects.
81
    Terminate(Arc<[u8]>),
82
}
83
84
19
fn encode_broadcast(message: &DaemonToClient) -> Arc<[u8]> {
85
19
    return Arc::from(
86
19
        encode_frame(message, DEFAULT_MAX_FRAME_LEN).expect("Daemon messages fit in a frame"),
87
    );
88
19
}
89
90
4
fn to_run_state(state: ClientState) -> ClientRunState {
91
4
    match state {
92
1
        ClientState::Active => return ClientRunState::Active,
93
3
        ClientState::Disabled => return ClientRunState::Disabled,
94
    }
95
4
}
96
97
/// Bits in `KEY_EVENT_RECORD::dwControlKeyState` that represent
98
/// "real" modifier keys (Ctrl / Alt / Shift) as opposed to lock
99
/// toggles (`CAPSLOCK_ON`, `NUMLOCK_ON`, `SCROLLLOCK_ON`) or the
100
/// `ENHANCED_KEY` flag.
101
///
102
/// Control-mode key classification ANDs `dwControlKeyState` with
103
/// this mask before matching; otherwise an enabled CapsLock or
104
/// NumLock would make `dwControlKeyState` non-zero and silently
105
/// skip every `(VK_*, 0)` arm.
106
const MODIFIER_MASK: u32 =
107
    LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED | LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED | SHIFT_PRESSED;
108
109
/// Top-level control-mode action a keystroke classifies into.
110
///
111
/// Extracted from [`Daemon::handle_input_record`]'s dispatch match
112
/// so the classification - including the [`MODIFIER_MASK`] step -
113
/// can be regression tested without instantiating a full
114
/// [`Daemon`].
115
#[derive(Debug, PartialEq, Eq)]
116
enum ControlModeAction {
117
    /// `[r]` - rearrange every client window.
118
    Retile,
119
    /// `[e]` - open the enable/disable input submenu.
120
    OpenEnableDisableSubmenu,
121
    /// `[t]` - flip each client's [`ClientState`].
122
    ToggleEnabled,
123
    /// `[n]` - force every client back to [`ClientState::Active`].
124
    EnableAll,
125
    /// `[c]` - prompt for new hostnames and launch additional clients.
126
    CreateWindows,
127
    /// `[h]` - copy the active clients' hostnames to the clipboard.
128
    CopyHostnames,
129
    /// Any other key in the active control-mode prompt.
130
    NoOp,
131
}
132
133
/// Enable/disable-submenu action a keystroke classifies into.
134
///
135
/// Extracted from [`Daemon::handle_enable_disable_submenu_key`]'s
136
/// dispatch match for the same reason as [`ControlModeAction`].
137
#[derive(Debug, PartialEq, Eq)]
138
enum EnableDisableSubmenuAction {
139
    /// `[e]` - force the targeted client(s) to [`ClientState::Active`].
140
    Enable,
141
    /// `[d]` - force the targeted client(s) to [`ClientState::Disabled`].
142
    Disable,
143
    /// `[t]` - flip the targeted client(s)' [`ClientState`].
144
    Toggle,
145
    /// Arrow key or vim motion - move the submenu's selection cursor.
146
    Navigate(NavigationDirection),
147
    /// Any other key while the submenu is open.
148
    NoOp,
149
}
150
151
/// Direction of a navigation keystroke inside the enable/disable
152
/// submenu.
153
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
154
enum NavigationDirection {
155
    Up,
156
    Down,
157
    Left,
158
    Right,
159
}
160
161
/// Classifies a top-level control-mode keystroke.
162
///
163
/// `control_key_state` is ANDed with [`MODIFIER_MASK`] so lock
164
/// toggles (`CAPSLOCK_ON`, `NUMLOCK_ON`, `SCROLLLOCK_ON`) and the
165
/// `ENHANCED_KEY` flag never bleed into the match - the
166
/// `(VK_*, 0)` arms must still fire while any of those bits are
167
/// set. Any "real" modifier bit (Ctrl / Alt / Shift) survives the
168
/// mask and falls through to [`ControlModeAction::NoOp`].
169
///
170
/// # Arguments
171
///
172
/// * `virtual_key`       - The pressed key's [`VIRTUAL_KEY`].
173
/// * `control_key_state` - The raw `dwControlKeyState` field from
174
///                         the [`KEY_EVENT_RECORD`].
175
///
176
/// # Returns
177
///
178
/// The [`ControlModeAction`] the dispatch should execute.
179
78
fn classify_control_mode_key(
180
78
    virtual_key: VIRTUAL_KEY,
181
78
    control_key_state: u32,
182
78
) -> ControlModeAction {
183
78
    return match (virtual_key, control_key_state & MODIFIER_MASK) {
184
6
        (VK_R, 0) => ControlModeAction::Retile,
185
6
        (VK_E, 0) => ControlModeAction::OpenEnableDisableSubmenu,
186
6
        (VK_T, 0) => ControlModeAction::ToggleEnabled,
187
6
        (VK_N, 0) => ControlModeAction::EnableAll,
188
6
        (VK_C, 0) => ControlModeAction::CreateWindows,
189
6
        (VK_H, 0) => ControlModeAction::CopyHostnames,
190
42
        _ => ControlModeAction::NoOp,
191
    };
192
78
}
193
194
/// Classifies an enable/disable-submenu keystroke.
195
///
196
/// See [`classify_control_mode_key`] for the [`MODIFIER_MASK`]
197
/// rationale; the same lock-state / `ENHANCED_KEY` masking applies
198
/// to the submenu so its `[e]`, `[d]`, `[t]` bindings keep working
199
/// regardless of lock state.
200
///
201
/// # Arguments
202
///
203
/// * `virtual_key`       - The pressed key's [`VIRTUAL_KEY`].
204
/// * `control_key_state` - The raw `dwControlKeyState` field from
205
///                         the [`KEY_EVENT_RECORD`].
206
///
207
/// # Returns
208
///
209
/// The [`EnableDisableSubmenuAction`] the dispatch should execute.
210
154
fn classify_enable_disable_submenu_key(
211
154
    virtual_key: VIRTUAL_KEY,
212
154
    control_key_state: u32,
213
154
) -> EnableDisableSubmenuAction {
214
154
    return match (virtual_key, control_key_state & MODIFIER_MASK) {
215
10
        (VK_E, 0) => EnableDisableSubmenuAction::Enable,
216
7
        (VK_D, 0) => EnableDisableSubmenuAction::Disable,
217
8
        (VK_T, 0) => EnableDisableSubmenuAction::Toggle,
218
13
        (VK_UP, 0) | (VK_K, 0) => EnableDisableSubmenuAction::Navigate(NavigationDirection::Up),
219
14
        (VK_DOWN, 0) | (VK_J, 0) => EnableDisableSubmenuAction::Navigate(NavigationDirection::Down),
220
12
        (VK_LEFT, 0) | (VK_H, 0) => EnableDisableSubmenuAction::Navigate(NavigationDirection::Left),
221
        (VK_RIGHT, 0) | (VK_L, 0) => {
222
12
            EnableDisableSubmenuAction::Navigate(NavigationDirection::Right)
223
        }
224
78
        _ => EnableDisableSubmenuAction::NoOp,
225
    };
226
154
}
227
228
/// Representation of a client
229
#[derive(Clone)]
230
struct Client {
231
    /// Hostname the client is connect to (or supposed to connect to).
232
    hostname: String,
233
    /// Window handle to the clients console window.
234
    window_handle: HWND,
235
    /// Process handle to the client process.
236
    process_handle: HANDLE,
237
    /// Process id of the client process.
238
    ///
239
    /// Used by the pipe server task to correlate which client has connected
240
    /// to it, via a handshake over the named pipe.
241
    process_id: u32,
242
    /// Authoritative source for this client's [`ClientState`].
243
    ///
244
    /// The daemon broadcasts new state values through the [`watch::Sender`];
245
    /// the assigned pipe-server task subscribes upon successful PID
246
    /// correlation and forwards every change to the client over the named
247
    /// pipe. [`watch::Sender`] is itself [`Clone`], so cloning a [`Client`]
248
    /// produces another sender that drives the same channel.
249
    state_sender: watch::Sender<ClientState>,
250
    /// Authoritative source for this client's highlight flag, set while
251
    /// the client is the daemon's currently selected submenu client.
252
    /// Visual only; input gating uses [`Client::state_sender`].
253
    highlight_sender: watch::Sender<bool>,
254
    /// Index passed to [`arrange_client_window`] when this client's
255
    /// on-screen position was last computed. Survives
256
    /// [`Clients::retain`] so the submenu navigation grid keeps
257
    /// matching the visible layout until the next retile.
258
    tile_index: usize,
259
}
260
261
unsafe impl Send for Client {}
262
263
/// Collection of [`Client`]s maintaining insertion order and a PID-indexed
264
/// lookup table.
265
///
266
/// The ordered list preserves client window placement semantics, while the
267
/// index enables O(1) lookup by process id - required by the pipe server task
268
/// during PID correlation and future per-client pipe server control.
269
struct Clients {
270
    /// Ordered list of clients; order matches launch order and is used for
271
    /// window arrangement and z-order synchronization.
272
    list: Vec<Client>,
273
    /// Maps a client's process id to its index in [`list`](Clients::list).
274
    pid_index: HashMap<u32, usize>,
275
    /// `number_of_consoles` value the current on-screen layout was
276
    /// computed with. Drives [`grid_dimensions`] for the submenu nav.
277
    /// Updated when the tiler positions windows
278
    /// ([`Clients::reset_tile_layout`]); preserved across
279
    /// [`Clients::retain`] so a closed-but-not-retiled window leaves
280
    /// a visible gap in the grid too.
281
    layout_n: usize,
282
}
283
284
impl Clients {
285
    /// Creates a new empty collection.
286
23
    fn new() -> Self {
287
23
        return Clients {
288
23
            list: Vec::new(),
289
23
            pid_index: HashMap::new(),
290
23
            layout_n: 0,
291
23
        };
292
23
    }
293
294
    /// Appends a client to the collection and records its position in the
295
    /// PID index.
296
    ///
297
    /// # Arguments
298
    ///
299
    /// * `client` - The [`Client`] to add.
300
    ///
301
    /// # Panics
302
    ///
303
    /// Panics if a client with the same process id is already present, as
304
    /// duplicate PIDs indicate broken daemon bookkeeping.
305
55
    fn push(&mut self, mut client: Client) {
306
55
        let index = self.list.len();
307
55
        assert!(
308
55
            !self.pid_index.contains_key(&client.process_id),
309
            "Duplicate client PID {} - daemon bookkeeping broken",
310
            client.process_id,
311
        );
312
        // Push assumes the new client occupies the next cell in a dense
313
        // layout - matching what the tiler does at initial launch and
314
        // right after `[c]reate`. `retain` leaves these values alone so
315
        // closed-but-not-retiled gaps stay visible to the navigation
316
        // grid. The next retile renumbers everything dense again.
317
54
        client.tile_index = index;
318
54
        self.pid_index.insert(client.process_id, index);
319
54
        self.list.push(client);
320
54
        self.layout_n = self.list.len();
321
54
    }
322
323
    /// Reassigns dense [`Client::tile_index`] values to `valid_pids` in
324
    /// the supplied order and snapshots the new [`Clients::layout_n`].
325
    ///
326
    /// Called by [`Daemon::rearrange_client_windows`] right before it
327
    /// re-positions the actual windows on screen, so navigation reads
328
    /// the same layout the tiler just applied.
329
    ///
330
    /// Invariant: `valid_pids` must cover every PID currently tracked
331
    /// in `self.list`. Passing a strict subset (e.g. a liveness-filtered
332
    /// list) would shrink `layout_n` while leaving stale `tile_index >=
333
    /// layout_n` values on the excluded clients, breaking the
334
    /// [`ClientGrid`] built from this collection. Drop dead clients
335
    /// via [`Clients::retain`] before retiling.
336
    ///
337
    /// # Arguments
338
    ///
339
    /// * `valid_pids` - PIDs of the clients that will be tiled, in the
340
    ///                  order they will be passed to
341
    ///                  [`arrange_client_window`].
342
1
    fn reset_tile_layout(&mut self, valid_pids: &[u32]) {
343
1
        debug_assert_eq!(
344
1
            valid_pids.len(),
345
1
            self.list.len(),
346
            "reset_tile_layout must receive every tracked client; \
347
             call Clients::retain to drop dead entries first",
348
        );
349
4
        for (index, pid) in 
valid_pids1
.
iter1
().
enumerate1
() {
350
4
            if let Some(&list_index) = self.pid_index.get(pid) {
351
4
                self.list[list_index].tile_index = index;
352
4
            
}0
353
        }
354
1
        self.layout_n = valid_pids.len();
355
1
    }
356
357
    /// Returns a reference to the client with the given process id, if any.
358
    ///
359
    /// # Arguments
360
    ///
361
    /// * `pid` - The process id of the client to look up.
362
    ///
363
    /// # Returns
364
    ///
365
    /// `Some(&Client)` if a client with the given PID exists, `None` otherwise.
366
35
    fn get_by_pid(&self, pid: u32) -> Option<&Client> {
367
35
        return self
368
35
            .pid_index
369
35
            .get(&pid)
370
35
            .map(|&index| return 
&self.list[index]30
);
371
35
    }
372
373
    /// Retains only the clients for which the predicate returns `true`,
374
    /// rebuilding the PID index to reflect the new positions.
375
    ///
376
    /// # Arguments
377
    ///
378
    /// * `f` - Predicate applied to each [`Client`]; kept when it returns `true`.
379
5
    fn retain<F: FnMut(&Client) -> bool>(&mut self, mut f: F) {
380
17
        
self.list5
.
retain5
(|client| return f(client));
381
5
        self.pid_index.clear();
382
10
        for (index, client) in 
self.list.iter()5
.
enumerate5
() {
383
10
            self.pid_index.insert(client.process_id, index);
384
10
        }
385
5
    }
386
}
387
388
/// Allows treating a [`Clients`] collection as a `&[Client]`, so callers can
389
/// use `&clients` where a slice is expected and get slice methods
390
/// (`iter`, `len`, `is_empty`, ...) via deref coercion.
391
impl std::ops::Deref for Clients {
392
    type Target = [Client];
393
394
46
    fn deref(&self) -> &[Client] {
395
46
        return &self.list;
396
46
    }
397
}
398
399
/// Consumes the collection and yields its clients in insertion order.
400
///
401
/// Used when merging a freshly launched [`Clients`] batch into an existing
402
/// collection while also spawning per-client pipe servers.
403
impl IntoIterator for Clients {
404
    type Item = Client;
405
    type IntoIter = std::vec::IntoIter<Client>;
406
407
0
    fn into_iter(self) -> Self::IntoIter {
408
0
        return self.list.into_iter();
409
0
    }
410
}
411
412
/// Hacky wrapper around a window handle.
413
///
414
/// As we cannot implement foreign traits for foreign structs
415
/// we introduce this wrapper to implement [Send] for [HWND].
416
#[derive(Debug, Eq)]
417
struct HWNDWrapper {
418
    hwdn: HWND,
419
}
420
421
unsafe impl Send for HWNDWrapper {}
422
423
impl PartialEq for HWNDWrapper {
424
    /// Returns whether to `HWNDWrapper` instances are equal or not
425
    /// based on the [HWND] they wrap.
426
2
    fn eq(&self, other: &Self) -> bool {
427
2
        return self.hwdn == other.hwdn;
428
2
    }
429
}
430
431
/// Returns a window handle to the current console window.
432
///
433
/// The [HWND] is wrapped in a `HWNDWrapper` so that
434
/// we can pass it inbetween threads.
435
0
fn get_console_window_wrapper(api: &dyn WindowsApi) -> HWNDWrapper {
436
0
    return HWNDWrapper {
437
0
        hwdn: api.get_console_window(),
438
0
    };
439
0
}
440
441
/// Returns a window handle to the foreground window.
442
///
443
/// The [HWND] is wrapped in a `HWNDWrapper` so that
444
/// we can pass it inbetween threads.
445
0
fn get_foreground_window_wrapper(api: &dyn WindowsApi) -> HWNDWrapper {
446
0
    return HWNDWrapper {
447
0
        hwdn: api.get_foreground_window(),
448
0
    };
449
0
}
450
451
/// Enum of all possible control mode states.
452
#[derive(PartialEq, Debug)]
453
enum ControlModeState {
454
    /// Controle mode is inactive.
455
    Inactive,
456
    /// One of the keys required for the control mode key combination
457
    /// is currently being pressed.
458
    Initiated,
459
    /// All required keys for the control mode key combination were pressed
460
    /// and control mode is now active.
461
    ///
462
    /// Active control mode prevents any input records from being sent to clients.
463
    Active,
464
    /// The user opened the `[e]nable/disable input` submenu from
465
    /// [`ControlModeState::Active`]; left only via `Esc`, which exits
466
    /// control mode entirely. `highlighted_pid` is the currently selected
467
    /// client (`None` when the cluster is empty); tracking by PID survives
468
    /// background-monitor `retain`s while the submenu is open.
469
    ///
470
    /// `anchor_col` is the upper-grid column carried across vertical
471
    /// moves so a Down + Up roundtrip across the partial-last-row
472
    /// boundary returns to the start cell. `None` while
473
    /// `highlighted_pid` is `None`.
474
    EnableDisableSubmenu {
475
        /// PID of the highlighted client, or `None` for an empty cluster.
476
        highlighted_pid: Option<u32>,
477
        /// Anchor upper-grid column carried across vertical moves.
478
        anchor_col: Option<i32>,
479
    },
480
}
481
482
/// The daemon is responsible to launch a client for
483
/// each host, positioning the client windows, forwarding
484
/// input records to all clients and handling control mode.
485
struct Daemon<'a> {
486
    /// A list of hostnames to connect to.
487
    hosts: Vec<String>,
488
    /// A username to use to connect to all clients.
489
    ///
490
    /// If it is empty the clients will use the SSH config to find an approriate
491
    /// username.
492
    username: Option<String>,
493
    /// Optional port used for all SSH connections.
494
    port: Option<u16>,
495
    /// The `DaemonConfig` that controls how the daemon console window looks like.
496
    config: &'a DaemonConfig,
497
    /// List of available cluster tags
498
    clusters: &'a [Cluster],
499
    /// The current control mode state. The submenu's selected client
500
    /// is carried inline on
501
    /// [`ControlModeState::EnableDisableSubmenu`] - tying its
502
    /// lifetime to the variant guarantees no stale highlight survives
503
    /// after `Esc`.
504
    control_mode_state: ControlModeState,
505
    /// If debug mode is enabled on the daemon it will also be enabled on all
506
    /// clients.
507
    debug: bool,
508
}
509
510
/// Compute the next submenu selection given a grid step.
511
///
512
/// Re-anchors on the first surviving client when `current_pid` is no
513
/// longer present (retained out while the submenu was open).
514
///
515
/// # Arguments
516
///
517
/// * `grid`        - Spatial grid view over the currently tracked clients.
518
/// * `current_pid` - PID currently highlighted, or `None`.
519
/// * `anchor_col`  - Anchor column carried from earlier moves.
520
/// * `direction`   - Direction the navigation keystroke encoded.
521
/// * `edge`        - Behavior when the move would leave the grid.
522
///
523
/// # Returns
524
///
525
/// `(new_pid, new_anchor_col)` to apply, or `(None, None)` for an empty
526
/// cluster.
527
33
fn next_submenu_selection(
528
33
    grid: &ClientGrid,
529
33
    current_pid: Option<u32>,
530
33
    anchor_col: Option<i32>,
531
33
    direction: NavigationDirection,
532
33
    edge: EdgeBehavior,
533
33
) -> (Option<u32>, Option<i32>) {
534
33
    if grid.is_empty() {
535
8
        return (None, None);
536
25
    }
537
25
    let 
current_pid23
= match current_pid.and_then(|pid| return grid.cell(pid)) {
538
23
        Some(cell) => cell.pid,
539
        None => {
540
2
            let first = grid.top_left_pid();
541
2
            let first_anchor = first
542
2
                .and_then(|pid| return grid.cell(pid))
543
2
                .map(|c| return grid.anchor_for(c));
544
2
            return (first, first_anchor);
545
        }
546
    };
547
23
    let anchor = anchor_col.unwrap_or_else(|| 
{0
548
0
        return grid
549
0
            .cell(current_pid)
550
0
            .map(|c| return grid.anchor_for(c))
551
0
            .unwrap_or(0);
552
0
    });
553
23
    return match grid.step(current_pid, anchor, direction, edge) {
554
23
        Some((pid, new_anchor)) => (Some(pid), Some(new_anchor)),
555
0
        None => (Some(current_pid), Some(anchor)),
556
    };
557
33
}
558
559
/// Build a [`ClientGrid`] from `clients` and `workspace_area` using the
560
/// same aspect-ratio expression the tiler uses.
561
///
562
/// # Arguments
563
///
564
/// * `clients`                   - Currently tracked clients in launch order.
565
/// * `workspace_area`            - Available workspace minus the daemon console.
566
/// * `aspect_ratio_adjustment`   - The `aspect_ratio_adjustment` daemon config.
567
///
568
/// # Returns
569
///
570
/// A populated [`ClientGrid`].
571
3
fn build_client_grid(
572
3
    clients: &Clients,
573
3
    workspace_area: &workspace::WorkspaceArea,
574
3
    aspect_ratio_adjustment: f64,
575
3
) -> ClientGrid {
576
3
    let aspect = workspace_aspect_ratio(workspace_area);
577
3
    let layout_n = clients.layout_n as i32;
578
3
    let (cols, rows) = grid_dimensions(layout_n, aspect, aspect_ratio_adjustment);
579
3
    let cells: Vec<(u32, usize)> = clients
580
3
        .iter()
581
7
        .
map3
(|c| return (c.process_id, c.tile_index))
582
3
        .collect();
583
3
    return ClientGrid::from_tiled_pids(&cells, layout_n, cols, rows);
584
3
}
585
586
impl<'a> Daemon<'a> {
587
    /// Builds a minimal [`Daemon`] suitable for unit tests.
588
    ///
589
    /// Populates every field with defaults that do not touch the
590
    /// Windows API or the network. Tests pick the
591
    /// [`ControlModeState`] they need to exercise; everything else
592
    /// stays inert.
593
    #[cfg(test)]
594
16
    fn for_test(
595
16
        config: &'a DaemonConfig,
596
16
        clusters: &'a [Cluster],
597
16
        control_mode_state: ControlModeState,
598
16
    ) -> Self {
599
16
        return Self {
600
16
            hosts: Vec::new(),
601
16
            username: None,
602
16
            port: None,
603
16
            config,
604
16
            clusters,
605
16
            control_mode_state,
606
16
            debug: false,
607
16
        };
608
16
    }
609
610
    /// Launches all client windows and blocks on the main run loop.
611
    ///
612
    /// Sets up the daemon console by disabling processed input mode and applying
613
    /// the configured colors and dimensions.
614
    /// Once all client windows have successfully started the daemon console window
615
    /// is moved to the foreground and receives focus.
616
0
    async fn launch<W: WindowsApi + Clone + 'static>(mut self, windows_api: &W) {
617
0
        windows_api
618
0
            .set_console_title(format!("{PACKAGE_NAME} daemon").as_str())
619
0
            .unwrap();
620
0
        set_console_color(
621
0
            windows_api,
622
0
            CONSOLE_CHARACTER_ATTRIBUTES(self.config.console_color),
623
        );
624
0
        set_console_border_color(windows_api, COLORREF(0x000000FF));
625
626
0
        toggle_processed_input_mode(windows_api); // Disable processed input mode
627
628
0
        let workspace_area = workspace::get_workspace_area(windows_api, self.config.height);
629
630
0
        self.arrange_daemon_console(windows_api, &workspace_area);
631
632
        // Looks like on windows 10 re-arranging the console resets the console output buffer
633
0
        set_console_color(
634
0
            windows_api,
635
0
            CONSOLE_CHARACTER_ATTRIBUTES(self.config.console_color),
636
        );
637
638
0
        let mut clients = Arc::new(Mutex::new(
639
0
            launch_clients(
640
0
                windows_api,
641
0
                self.hosts.to_vec(),
642
0
                &self.username,
643
0
                self.port,
644
0
                self.debug,
645
0
                &workspace_area,
646
0
                self.config.aspect_ratio_adjustment,
647
0
                0,
648
0
            )
649
0
            .await,
650
        ));
651
652
        // Now that all clients started, focus the daemon console again.
653
0
        let daemon_console = windows_api.get_console_window();
654
0
        let _ = windows_api.bring_window_to_top(daemon_console, true);
655
656
0
        self.print_instructions(windows_api);
657
0
        self.run(windows_api, &mut clients, &workspace_area).await;
658
0
    }
659
660
    /// The main run loop of the `daemon` subcommand.
661
    ///
662
    /// Opens a multi-producer, multi-consumer broadcasting channel used to
663
    /// send the read input records in parallel to the name pipe servers
664
    /// the clients are listening on.
665
    /// Spawns a background thread that waits for all clients to terminate
666
    /// and then stops the current process.
667
    /// Spawns a background thread that ensures the z-order of all client
668
    /// windows is in sync with the daemon window.
669
    /// I.e. if the daemon window is focussed, all clients should be moved to the foreground.
670
    ///
671
    /// The main loop consists of waiting for input records to read from the keyboard,
672
    /// sending them to all clients and handling control mode.
673
    ///
674
    /// # Arguments
675
    ///
676
    /// * `windows_api`                     - The Windows API implementation to use
677
    /// * `clients`                         - A thread safe mapping from the number
678
    ///                                       a client console window was launched at
679
    ///                                       in relation to the other client windows
680
    ///                                       and the clients console window handle.
681
    /// * `workspace_area`                  - The available workspace area on the
682
    ///                                       primary monitor minus the space occupied
683
    ///                                       by the daemon console window.
684
0
    async fn run<W: WindowsApi + Clone + 'static>(
685
0
        &mut self,
686
0
        windows_api: &W,
687
0
        clients: &mut Arc<Mutex<Clients>>,
688
0
        workspace_area: &workspace::WorkspaceArea,
689
0
    ) {
690
0
        let (sender, _) = broadcast::channel::<ClientBroadcast>(SENDER_CAPACITY);
691
692
0
        let mut servers = Arc::new(Mutex::new(
693
0
            self.launch_named_pipe_servers(&sender, Arc::clone(clients)),
694
        ));
695
696
        // Monitor client processes
697
0
        let clients_clone = Arc::clone(clients);
698
0
        let windows_api_clone = windows_api.clone();
699
0
        let sender_clone = sender.clone();
700
0
        tokio::spawn(async move {
701
            loop {
702
0
                clients_clone.lock().unwrap().retain(|client| {
703
0
                    match windows_api_clone.get_exit_code(client.process_handle) {
704
0
                        Ok(exit_code) => return exit_code == STILL_ACTIVE.0 as u32,
705
0
                        Err(_) => return false, // Process handle is invalid, remove client
706
                    }
707
0
                });
708
0
                if clients_clone.lock().unwrap().is_empty() {
709
0
                    let _ = sender_clone.send(ClientBroadcast::Terminate(encode_broadcast(
710
0
                        &DaemonToClient::Terminate {
711
0
                            reason: "all clients exited".to_string(),
712
0
                        },
713
0
                    )));
714
0
                    std::process::exit(0);
715
0
                }
716
0
                tokio::time::sleep(Duration::from_millis(5)).await;
717
            }
718
        });
719
720
0
        ensure_client_z_order_in_sync_with_daemon(
721
0
            Arc::new(windows_api.clone()),
722
0
            clients.to_owned(),
723
        );
724
725
        loop {
726
0
            self.handle_input_record(
727
0
                windows_api,
728
0
                &sender,
729
0
                read_keyboard_input(windows_api),
730
0
                clients,
731
0
                workspace_area,
732
0
                &mut servers,
733
0
            )
734
0
            .await;
735
        }
736
    }
737
738
    /// Launch a named pipe server for each host in a dedicated thread.
739
    ///
740
    /// # Arguments
741
    ///
742
    /// * `sender` - The sender end of the broadcast channel through which
743
    ///              the main thread will send the input records that are to
744
    ///              be forwarded to the clients.
745
    ///
746
    /// # Returns
747
    ///
748
    /// Returns a list of [JoinHandle]s, one handle for each thread.
749
0
    fn launch_named_pipe_servers(
750
0
        &self,
751
0
        sender: &Sender<ClientBroadcast>,
752
0
        clients: Arc<Mutex<Clients>>,
753
0
    ) -> Vec<JoinHandle<()>> {
754
0
        let mut servers: Vec<JoinHandle<()>> = Vec::new();
755
0
        for _ in &self.hosts {
756
0
            self.launch_named_pipe_server(&mut servers, sender, Arc::clone(&clients));
757
0
        }
758
0
        return servers;
759
0
    }
760
761
    /// Launch a named pipe server in a dedicated thread.
762
    ///
763
    /// # Arguments
764
    ///
765
    /// * `servers` - A list of [JoinHandle]s to which the join handle for
766
    ///               the new thread will be added.
767
    /// * `sender`  - The sender end of the broadcast channel through which
768
    ///               the main thread will send the input records that are to
769
    ///               be forwarded to the clients.
770
0
    fn launch_named_pipe_server(
771
0
        &self,
772
0
        servers: &mut Vec<JoinHandle<()>>,
773
0
        sender: &Sender<ClientBroadcast>,
774
0
        clients: Arc<Mutex<Clients>>,
775
0
    ) {
776
0
        let named_pipe_server =
777
0
            WindowsControlChannelServer::bind(&control_endpoint(std::process::id()))
778
0
                .unwrap_or_else(|err| {
779
0
                    error!("{}", err);
780
0
                    panic!("Failed to create named pipe server",)
781
                });
782
0
        let mut receiver = sender.subscribe();
783
0
        servers.push(tokio::spawn(async move {
784
0
            named_pipe_server_routine(named_pipe_server, &mut receiver, clients).await;
785
0
        }));
786
0
    }
787
788
    /// Handle the given input record.
789
    ///
790
    /// Input records are being forwarded to all clients.
791
    /// If a sequence of input records matches the control mode
792
    /// key combination, forwarding is temporarily interrupted,
793
    /// until control mode is exited.
794
    ///
795
    /// # Arguments
796
    ///
797
    /// * `sender`                          - The sender end of the broadcast channel
798
    ///                                       through which we will send the input records
799
    ///                                       that are being forwarded to the clients
800
    ///                                       by the named pipe servers (`servers`).
801
    /// * `input_record`                    - The [INPUT_RECORD_0].`KeyEvent` read from the
802
    ///                                       console input buffer.
803
    /// * `clients`                         - A thread safe mapping from the number
804
    ///                                       a client console window was launched at
805
    ///                                       in relation to the other client windows
806
    ///                                       and the clients console window handle.
807
    ///                                       The mapping will be extended if additional clients
808
    ///                                       are being added through control mode `[c]reate window(s)`.
809
    /// * `workspace_area`                  - The available workspace area on the
810
    ///                                       primary monitor minus the space occupied
811
    ///                                       by the daemon console window.
812
    /// * `servers`                         - A thread safe list of [JoinHandle]s,
813
    ///                                       one handle for each named pipe server background thread.
814
    ///                                       The list will be extended if additional clients are being added
815
    ///                                       through control mode `[c]reate window(s)`.
816
0
    async fn handle_input_record<W: WindowsApi + Clone + 'static>(
817
0
        &mut self,
818
0
        windows_api: &W,
819
0
        sender: &Sender<ClientBroadcast>,
820
0
        input_record: INPUT_RECORD_0,
821
0
        clients: &mut Arc<Mutex<Clients>>,
822
0
        workspace_area: &workspace::WorkspaceArea,
823
0
        servers: &mut Arc<Mutex<Vec<JoinHandle<()>>>>,
824
0
    ) {
825
0
        if self.control_mode_is_active(windows_api, clients, input_record) {
826
0
            if self.control_mode_state == ControlModeState::Initiated {
827
0
                clear_screen(windows_api);
828
0
                println!("Control Mode (Esc to exit)");
829
0
                println!(
830
                    "[c]reate window(s), [r]etile, [e]nable/disable input, [t]oggle enabled, e[n]able all, copy active [h]ostname(s)"
831
                );
832
0
                self.control_mode_state = ControlModeState::Active;
833
0
                return;
834
0
            }
835
0
            let key_event = unsafe { input_record.KeyEvent };
836
0
            if !key_event.bKeyDown.as_bool() {
837
0
                return;
838
0
            }
839
0
            if matches!(
840
0
                self.control_mode_state,
841
                ControlModeState::EnableDisableSubmenu { .. }
842
            ) {
843
0
                self.handle_enable_disable_submenu_key(
844
0
                    windows_api,
845
0
                    clients,
846
0
                    workspace_area,
847
0
                    key_event,
848
                );
849
0
                return;
850
0
            }
851
0
            match classify_control_mode_key(
852
0
                VIRTUAL_KEY(key_event.wVirtualKeyCode),
853
0
                key_event.dwControlKeyState,
854
0
            ) {
855
0
                ControlModeAction::Retile => {
856
0
                    self.rearrange_client_windows(
857
0
                        windows_api,
858
0
                        &mut clients.lock().unwrap(),
859
0
                        workspace_area,
860
0
                    );
861
0
                    self.arrange_daemon_console(windows_api, workspace_area);
862
0
                }
863
                ControlModeAction::OpenEnableDisableSubmenu => {
864
0
                    let clients_guard = clients.lock().unwrap();
865
0
                    let grid = build_client_grid(
866
0
                        &clients_guard,
867
0
                        workspace_area,
868
0
                        self.config.aspect_ratio_adjustment,
869
                    );
870
0
                    let next_pid = grid.top_left_pid();
871
0
                    let anchor_col = next_pid
872
0
                        .and_then(|p| return grid.cell(p))
873
0
                        .map(|c| return grid.anchor_for(c));
874
0
                    self.apply_submenu_highlight(&clients_guard, None, next_pid);
875
0
                    self.control_mode_state = ControlModeState::EnableDisableSubmenu {
876
0
                        highlighted_pid: next_pid,
877
0
                        anchor_col,
878
0
                    };
879
0
                    self.render_enable_disable_submenu(windows_api);
880
                }
881
                ControlModeAction::ToggleEnabled => {
882
                    // Snapshot before flipping so each client toggles relative
883
                    // to its own pre-loop state, not to writes this loop has
884
                    // already made.
885
0
                    self.update_client_states(clients, |clients_guard| {
886
0
                        return clients_guard
887
0
                            .iter()
888
0
                            .map(|client| {
889
0
                                let flipped = match *client.state_sender.borrow() {
890
0
                                    ClientState::Active => ClientState::Disabled,
891
0
                                    ClientState::Disabled => ClientState::Active,
892
                                };
893
0
                                return (client.process_id, flipped);
894
0
                            })
895
0
                            .collect();
896
0
                    });
897
0
                    self.quit_control_mode(windows_api);
898
                }
899
                ControlModeAction::EnableAll => {
900
0
                    self.update_client_states(clients, |clients_guard| {
901
0
                        return clients_guard
902
0
                            .iter()
903
0
                            .map(|client| return (client.process_id, ClientState::Active))
904
0
                            .collect();
905
0
                    });
906
0
                    self.quit_control_mode(windows_api);
907
                }
908
                ControlModeAction::CreateWindows => {
909
0
                    clear_screen(windows_api);
910
                    // TODO: make ESC abort
911
0
                    println!("Hostname(s) or cluster tag(s): (leave empty to abort)");
912
0
                    toggle_processed_input_mode(windows_api); // As it was disabled before, this enables it again
913
0
                    let mut hostnames = String::new();
914
0
                    match io::stdin().read_line(&mut hostnames) {
915
0
                        Ok(2) => {
916
0
                            // Empty input (only newline '\n')
917
0
                        }
918
                        Ok(_) => {
919
0
                            let number_of_existing_clients = clients.lock().unwrap().len();
920
0
                            let new_clients = launch_clients(
921
0
                                windows_api,
922
0
                                expand_hosts(
923
0
                                    hostnames.split(' ').map(|x| return x.trim()).collect(),
924
0
                                    self.clusters,
925
                                ),
926
0
                                &self.username,
927
0
                                self.port,
928
0
                                self.debug,
929
0
                                workspace_area,
930
0
                                self.config.aspect_ratio_adjustment,
931
0
                                number_of_existing_clients,
932
                            )
933
0
                            .await;
934
0
                            for client in new_clients.into_iter() {
935
0
                                clients.lock().unwrap().push(client);
936
0
                                self.launch_named_pipe_server(
937
0
                                    &mut servers.lock().unwrap(),
938
0
                                    sender,
939
0
                                    Arc::clone(clients),
940
0
                                );
941
0
                            }
942
                        }
943
0
                        Err(error) => {
944
0
                            error!("{error}");
945
                        }
946
                    }
947
0
                    toggle_processed_input_mode(windows_api); // Re-disable processed input mode.
948
0
                    self.rearrange_client_windows(
949
0
                        windows_api,
950
0
                        &mut clients.lock().unwrap(),
951
0
                        workspace_area,
952
                    );
953
0
                    self.arrange_daemon_console(windows_api, workspace_area);
954
                    // Focus the daemon console again.
955
0
                    let daemon_window = windows_api.get_console_window();
956
0
                    let _ = windows_api.bring_window_to_top(daemon_window, true);
957
0
                    self.quit_control_mode(windows_api);
958
                }
959
                ControlModeAction::CopyHostnames => {
960
0
                    let mut active_hostnames: Vec<String> = vec![];
961
0
                    for client in clients.lock().unwrap().iter() {
962
0
                        if windows_api.is_window(client.window_handle) {
963
0
                            active_hostnames.push(client.hostname.clone());
964
0
                        }
965
                    }
966
0
                    cli_clipboard::set_contents(active_hostnames.join(" ")).unwrap();
967
0
                    self.quit_control_mode(windows_api);
968
                }
969
0
                ControlModeAction::NoOp => {}
970
            }
971
0
            return;
972
0
        }
973
0
        let key_event = unsafe { input_record.KeyEvent };
974
0
        if !key_event.bKeyDown.as_bool() {
975
0
            return;
976
0
        }
977
0
        let frame = encode_broadcast(&input::key_event_to_message(&key_event));
978
0
        match sender.send(ClientBroadcast::Keystroke(frame)) {
979
0
            Ok(_) => {}
980
0
            Err(_) => {
981
0
                thread::sleep(time::Duration::from_nanos(1));
982
0
            }
983
        }
984
0
    }
985
986
    /// Updates `self.control_mode_state` for the given input record and
987
    /// reports whether control mode owned the keystroke.
988
    ///
989
    /// Entering control mode requires this function to be called twice
990
    /// because the activating chord `Ctrl + A` produces two input
991
    /// records (the modifier press and the `A` key). Once active, every
992
    /// subsequent key - including the `Esc` that exits control mode -
993
    /// is reported as consumed so callers do not forward it to clients.
994
    ///
995
    /// # Arguments
996
    ///
997
    /// * `windows_api`  - The Windows API implementation to use.
998
    /// * `clients`      - Currently tracked clients. Used to clear the
999
    ///                    submenu highlight on the previously-selected
1000
    ///                    client when `Esc` exits the enable/disable
1001
    ///                    submenu.
1002
    /// * `input_record` - A KeyEvent input record.
1003
    ///
1004
    /// # Returns
1005
    ///
1006
    /// Whether the input record was consumed by control mode. Returns
1007
    /// `true` while control mode is active (including the `Esc`
1008
    /// keystroke that exits it), so callers must not forward such
1009
    /// records to clients.
1010
1
    fn control_mode_is_active<W: WindowsApi>(
1011
1
        &mut self,
1012
1
        windows_api: &W,
1013
1
        clients: &Mutex<Clients>,
1014
1
        input_record: INPUT_RECORD_0,
1015
1
    ) -> bool {
1016
1
        let key_event = unsafe { input_record.KeyEvent };
1017
1
        if self.control_mode_state == ControlModeState::Active
1018
0
            || matches!(
1019
0
                self.control_mode_state,
1020
                ControlModeState::EnableDisableSubmenu { .. }
1021
            )
1022
        {
1023
1
            if key_event.wVirtualKeyCode == VK_ESCAPE.0 {
1024
                if let ControlModeState::EnableDisableSubmenu {
1025
0
                    highlighted_pid, ..
1026
1
                } = self.control_mode_state
1027
0
                {
1028
0
                    let clients_guard = clients.lock().unwrap();
1029
0
                    self.apply_submenu_highlight(&clients_guard, highlighted_pid, None);
1030
1
                }
1031
1
                self.quit_control_mode(windows_api);
1032
1
                return true;
1033
0
            }
1034
0
            return true;
1035
0
        }
1036
0
        if (key_event.dwControlKeyState & LEFT_CTRL_PRESSED >= 1
1037
0
            || key_event.dwControlKeyState & RIGHT_CTRL_PRESSED >= 1)
1038
0
            && key_event.wVirtualKeyCode == VK_A.0
1039
        {
1040
0
            self.control_mode_state = ControlModeState::Initiated;
1041
0
            return true;
1042
0
        }
1043
0
        return false;
1044
1
    }
1045
1046
    /// Prints the default daemon instructions to the daemon console.
1047
    ///
1048
    /// # Arguments
1049
    ///
1050
    /// * `windows_api` - Windows API used to clear and redraw the
1051
    ///                   daemon console.
1052
2
    fn quit_control_mode<W: WindowsApi>(&mut self, windows_api: &W) {
1053
2
        self.print_instructions(windows_api);
1054
2
        self.control_mode_state = ControlModeState::Inactive;
1055
2
    }
1056
1057
    /// Clears the console screen and prints the default daemon instructions.
1058
2
    fn print_instructions<W: WindowsApi>(&self, windows_api: &W) {
1059
2
        clear_screen(windows_api);
1060
2
        println!("Input to terminal: (Ctrl-A to enter control mode)");
1061
2
    }
1062
1063
    /// Iterates over all still open client windows and re-arranges them
1064
    /// on the screen based on the aspect ration adjustment daemon configuration.
1065
    ///
1066
    /// Client windows will be re-sized and re-positioned.
1067
    ///
1068
    /// # Arguments
1069
    ///
1070
    /// * `windows_api`                     - The Windows API implementation to use
1071
    /// * `clients`                         - A thread safe mapping from the number
1072
    ///                                       a client console window was launched at
1073
    ///                                       in relation to the other client windows
1074
    ///                                       and the clients console window handle.
1075
    ///                                       The number is relevant to determine the
1076
    ///                                       position on the screen the window should
1077
    ///                                       be placed at.
1078
    /// * `workspace_area`                  - The available workspace area on the
1079
    ///                                       primary monitor minus the space occupied
1080
    ///                                       by the daemon console window.
1081
0
    fn rearrange_client_windows<W: WindowsApi>(
1082
0
        &self,
1083
0
        windows_api: &W,
1084
0
        clients: &mut Clients,
1085
0
        workspace_area: &workspace::WorkspaceArea,
1086
0
    ) {
1087
0
        clients.retain(|client| {
1088
0
            let exit_code = match windows_api.get_exit_code(client.process_handle) {
1089
0
                Ok(code) => code,
1090
0
                Err(_) => return false,
1091
            };
1092
0
            return exit_code == STILL_ACTIVE.0 as u32
1093
0
                && windows_api.is_window(client.window_handle);
1094
0
        });
1095
0
        let valid_layout: Vec<(u32, HWND)> = clients
1096
0
            .iter()
1097
0
            .map(|c| return (c.process_id, c.window_handle))
1098
0
            .collect();
1099
0
        let valid_pids: Vec<u32> = valid_layout.iter().map(|(pid, _)| return *pid).collect();
1100
0
        clients.reset_tile_layout(&valid_pids);
1101
0
        for (index, (_, window_handle)) in valid_layout.iter().enumerate() {
1102
0
            arrange_client_window(
1103
0
                windows_api,
1104
0
                window_handle,
1105
0
                workspace_area,
1106
0
                index,
1107
0
                valid_layout.len(),
1108
0
                self.config.aspect_ratio_adjustment,
1109
            )
1110
        }
1111
0
    }
1112
1113
    /// Dispatches a key press received while the daemon is in the
1114
    /// [`ControlModeState::EnableDisableSubmenu`] state. `[e]/[d]/[t]`
1115
    /// act on the currently selected client; `Navigate` moves the
1116
    /// selection and redraws the prompt. The submenu is left via
1117
    /// `ESC`, which is handled by the caller.
1118
    ///
1119
    /// # Arguments
1120
    ///
1121
    /// * `windows_api` - Windows API implementation used by the
1122
    ///                   render helper when redrawing after navigation.
1123
    /// * `clients`     - Shared client collection. Empty lists are a
1124
    ///                   no-op for every action.
1125
    /// * `key_event`   - The key-down [`KEY_EVENT_RECORD`] dispatched
1126
    ///                   from `handle_input_record`.
1127
11
    fn handle_enable_disable_submenu_key<W: WindowsApi>(
1128
11
        &mut self,
1129
11
        windows_api: &W,
1130
11
        clients: &Mutex<Clients>,
1131
11
        workspace_area: &workspace::WorkspaceArea,
1132
11
        key_event: KEY_EVENT_RECORD,
1133
11
    ) {
1134
        let ControlModeState::EnableDisableSubmenu {
1135
11
            highlighted_pid,
1136
11
            anchor_col,
1137
11
        } = self.control_mode_state
1138
        else {
1139
0
            return;
1140
        };
1141
11
        match classify_enable_disable_submenu_key(
1142
11
            VIRTUAL_KEY(key_event.wVirtualKeyCode),
1143
11
            key_event.dwControlKeyState,
1144
11
        ) {
1145
            EnableDisableSubmenuAction::Enable => {
1146
4
                self.update_client_states(clients, |clients_guard| {
1147
4
                    return highlighted_pid
1148
4
                        .and_then(|pid| return 
clients_guard3
.
get_by_pid3
(
pid3
))
1149
4
                        .map(|client| return 
vec!3
[
(client.process_id, ClientState::Active)3
])
1150
4
                        .unwrap_or_default();
1151
4
                });
1152
            }
1153
            EnableDisableSubmenuAction::Disable => {
1154
1
                self.update_client_states(clients, |clients_guard| {
1155
1
                    return highlighted_pid
1156
1
                        .and_then(|pid| return clients_guard.get_by_pid(pid))
1157
1
                        .map(|client| return vec![(client.process_id, ClientState::Disabled)])
1158
1
                        .unwrap_or_default();
1159
1
                });
1160
            }
1161
            EnableDisableSubmenuAction::Toggle => {
1162
2
                self.update_client_states(clients, |clients_guard| {
1163
2
                    return highlighted_pid
1164
2
                        .and_then(|pid| return clients_guard.get_by_pid(pid))
1165
2
                        .map(|client| {
1166
2
                            let flipped = match *client.state_sender.borrow() {
1167
1
                                ClientState::Active => ClientState::Disabled,
1168
1
                                ClientState::Disabled => ClientState::Active,
1169
                            };
1170
2
                            return vec![(client.process_id, flipped)];
1171
2
                        })
1172
2
                        .unwrap_or_default();
1173
2
                });
1174
            }
1175
3
            EnableDisableSubmenuAction::Navigate(direction) => {
1176
3
                let clients_guard = clients.lock().unwrap();
1177
3
                let grid = build_client_grid(
1178
3
                    &clients_guard,
1179
3
                    workspace_area,
1180
3
                    self.config.aspect_ratio_adjustment,
1181
3
                );
1182
3
                let (next_pid, next_anchor) = next_submenu_selection(
1183
3
                    &grid,
1184
3
                    highlighted_pid,
1185
3
                    anchor_col,
1186
3
                    direction,
1187
3
                    self.config.submenu_edge_behavior,
1188
3
                );
1189
3
                self.apply_submenu_highlight(&clients_guard, highlighted_pid, next_pid);
1190
3
                self.control_mode_state = ControlModeState::EnableDisableSubmenu {
1191
3
                    highlighted_pid: next_pid,
1192
3
                    anchor_col: next_anchor,
1193
3
                };
1194
3
                self.render_enable_disable_submenu(windows_api);
1195
3
            }
1196
1
            EnableDisableSubmenuAction::NoOp => {}
1197
        }
1198
11
    }
1199
1200
    /// Redraws the enable/disable submenu prompt.
1201
    ///
1202
    /// # Arguments
1203
    ///
1204
    /// * `windows_api` - Windows API used to clear the console.
1205
3
    fn render_enable_disable_submenu<W: WindowsApi>(&self, windows_api: &W) {
1206
3
        clear_screen(windows_api);
1207
3
        println!("Enable/Disable input (Esc to exit)");
1208
3
        println!("[e]nable, [d]isable, [t]oggle, arrows/hjkl to move");
1209
3
    }
1210
1211
    /// Move the per-client highlight from `prev_pid` to `next_pid`.
1212
    ///
1213
    /// PID-based clearing tolerates the background monitor's `retain`
1214
    /// shifting indices while the submenu is open.
1215
    ///
1216
    /// # Arguments
1217
    ///
1218
    /// * `clients`  - Currently tracked clients.
1219
    /// * `prev_pid` - PID currently highlighted, or `None` if no
1220
    ///                client is highlighted.
1221
    /// * `next_pid` - PID to highlight now, or `None` to clear the
1222
    ///                highlight entirely.
1223
7
    fn apply_submenu_highlight(
1224
7
        &self,
1225
7
        clients: &Clients,
1226
7
        prev_pid: Option<u32>,
1227
7
        next_pid: Option<u32>,
1228
7
    ) {
1229
7
        if let Some(
prev_pid6
) = prev_pid {
1230
6
            if Some(prev_pid) != next_pid {
1231
6
                if let Some(
prev_client4
) = clients.get_by_pid(prev_pid) {
1232
4
                    prev_client.highlight_sender.send_replace(false);
1233
4
                
}2
1234
0
            }
1235
1
        }
1236
7
        if let Some(
next_pid6
) = next_pid {
1237
6
            if let Some(client) = clients.get_by_pid(next_pid) {
1238
6
                client.highlight_sender.send_replace(true);
1239
6
            
}0
1240
1
        }
1241
7
    }
1242
1243
    /// Apply a batch of [`ClientState`] updates while holding the
1244
    /// [`Clients`] mutex exactly once.
1245
    ///
1246
    /// `f` is called with the locked guard and returns the list of
1247
    /// `(pid, new_state)` updates to apply. The guard is held across both
1248
    /// the build and the apply phase so callers see a stable snapshot.
1249
    ///
1250
    /// # Arguments
1251
    ///
1252
    /// * `clients` - Shared client collection.
1253
    /// * `f`       - Builds the updates from a `&Clients` snapshot.
1254
7
    fn update_client_states<F>(&self, clients: &Mutex<Clients>, f: F)
1255
7
    where
1256
7
        F: FnOnce(&Clients) -> Vec<(u32, ClientState)>,
1257
    {
1258
7
        let clients_guard = clients.lock().unwrap();
1259
7
        let updates = f(&clients_guard);
1260
7
        for (
pid6
,
state6
) in updates {
1261
6
            self.set_client_state(&clients_guard, pid, state);
1262
6
        }
1263
7
    }
1264
1265
    /// Push a new [`ClientState`] for the client identified by `pid`.
1266
    ///
1267
    /// Looks the client up by PID and broadcasts the new state through its
1268
    /// [`watch::Sender`]. The pipe-server task subscribed to that sender
1269
    /// observes the change and forwards a v1 `StateChange`
1270
    /// frame to the client over the named pipe. Called from the
1271
    /// control-mode handlers for `[t]oggle enabled` and `e[n]able all` via
1272
    /// [`Daemon::update_client_states`].
1273
    ///
1274
    /// # Arguments
1275
    ///
1276
    /// * `clients` - The daemon's tracked clients.
1277
    /// * `pid`     - Process id of the client whose state should change.
1278
    /// * `state`   - The new state to broadcast.
1279
6
    fn set_client_state(&self, clients: &Clients, pid: u32, state: ClientState) {
1280
6
        if let Some(client) = clients.get_by_pid(pid) {
1281
6
            // `send_replace` always updates the stored value (unlike `send`,
1282
6
            // which returns `Err` and leaves the value untouched when there
1283
6
            // are no active receivers). This matters during the brief window
1284
6
            // between [`Client`] construction and the pipe-server task's
1285
6
            // `subscribe()`: any state change pushed in that window must
1286
6
            // still be visible to the next subscriber via `borrow`.
1287
6
            client.state_sender.send_replace(state);
1288
6
        
}0
1289
6
    }
1290
1291
    /// Re-sizes and re-positions the daemon console window on the screen
1292
    /// based on the daemon height configuration.
1293
    ///
1294
    /// # Arguments
1295
    ///
1296
    /// * `windows_api` - The Windows API implementation to use
1297
    /// * `workspace_area` - The available workspace area on the
1298
    ///                      primary monitor minus the space occupied
1299
    ///                      by the daemon console window.
1300
0
    fn arrange_daemon_console<W: WindowsApi>(
1301
0
        &self,
1302
0
        windows_api: &W,
1303
0
        workspace_area: &WorkspaceArea,
1304
0
    ) {
1305
0
        let (x, y, width, height) = get_console_rect(
1306
0
            0,
1307
0
            workspace_area.height,
1308
0
            workspace_area.width - (workspace_area.x_fixed_frame + workspace_area.x_size_frame),
1309
0
            self.config.height,
1310
0
            workspace_area,
1311
0
        );
1312
0
        arrange_console(windows_api, x, y, width, height);
1313
0
    }
1314
}
1315
1316
/// The processed console input mode controls whether special key combinations
1317
/// such as `Ctrl + c` or `Ctrl + BREAK` receive special handling or are treated
1318
/// as simple key presses.
1319
///
1320
/// By default processed input mode is enabled, meaning `Ctrl + c` is treated as
1321
/// a signal, not key presses.
1322
///
1323
/// <https://learn.microsoft.com/en-us/windows/console/ctrl-c-and-ctrl-break-signals>
1324
///
1325
/// # Arguments
1326
///
1327
/// * `windows_api` - The Windows API implementation to use
1328
0
fn toggle_processed_input_mode<W: WindowsApi>(windows_api: &W) {
1329
0
    let handle = get_console_input_buffer();
1330
0
    let mode = windows_api.get_console_mode(handle).unwrap();
1331
0
    let new_mode = windows::Win32::System::Console::CONSOLE_MODE(mode.0 ^ ENABLE_PROCESSED_INPUT.0);
1332
0
    let _ = windows_api.set_console_mode(handle, new_mode);
1333
0
}
1334
1335
/// Resolve cluster tags into hostnames
1336
///
1337
/// Iterates over the list of hosts to find and resolve cluster tags.
1338
/// Nested cluster tags are supported but recursivness is not checked for.
1339
///
1340
/// # Arguments
1341
///
1342
/// * `hosts`       - List of hosts including hostnames and or cluster tags
1343
/// * `clusters`    - List of available cluster tags
1344
///
1345
/// # Returns
1346
///
1347
/// A list of hostnames
1348
18
pub fn resolve_cluster_tags<'a>(hosts: Vec<&'a str>, clusters: &'a [Cluster]) -> Vec<&'a str> {
1349
18
    let mut resolved_hosts: Vec<&str> = Vec::new();
1350
    let mut is_cluster_tag: bool;
1351
31
    for host in 
hosts18
{
1352
31
        is_cluster_tag = false;
1353
31
        for 
cluster23
in clusters {
1354
23
            if host == cluster.name {
1355
5
                is_cluster_tag = true;
1356
5
                resolved_hosts.extend(resolve_cluster_tags(
1357
9
                    
cluster.hosts.iter()5
.
map5
(|host| return &**host).
collect5
(),
1358
5
                    clusters,
1359
                ));
1360
5
                break;
1361
18
            }
1362
        }
1363
31
        if !is_cluster_tag {
1364
26
            resolved_hosts.push(host);
1365
26
        
}5
1366
    }
1367
18
    return resolved_hosts;
1368
18
}
1369
1370
/// Resolve cluster tags in `hosts` and expand brace expressions
1371
/// (e.g. `host{1..3}.local`) in each resulting hostname.
1372
///
1373
/// Used by the control-mode `[c]reate window(s)` path so hostname
1374
/// input behaves the same as on the CLI. Each cluster-resolved
1375
/// hostname is passed through [`bracoxide::explode`] individually;
1376
/// hostnames that do not contain a brace expression are kept as-is.
1377
///
1378
/// # Arguments
1379
///
1380
/// * `hosts`    - User-supplied hostnames and/or cluster tags.
1381
/// * `clusters` - Available cluster definitions.
1382
///
1383
/// # Returns
1384
///
1385
/// The fully resolved, brace-expanded list of hostnames.
1386
4
pub fn expand_hosts(hosts: Vec<&str>, clusters: &[Cluster]) -> Vec<String> {
1387
4
    return resolve_cluster_tags(hosts, clusters)
1388
4
        .into_iter()
1389
7
        .
flat_map4
(|host| return explode(host).unwrap_or_else(|_| return
vec!4
[
host4
.
to_owned4
()]))
1390
4
        .collect();
1391
4
}
1392
1393
/// Launches a client console for each given host and waits for
1394
/// the client windows to exist before returning their handles.
1395
///
1396
/// # Arguments
1397
///
1398
/// * `windows_api`             - The Windows API implementation to use
1399
/// * `hosts`                   - List of hosts
1400
/// * `username`                - Optional username, if none is given
1401
///                               the client will use the SSH config to
1402
///                               determine a username.
1403
/// * `port`                    - Optional port for SSH connections
1404
/// * `debug`                   - Toggles debug mode on the client.
1405
/// * `workspace_area`          - The available workspace area on the primary monitor
1406
///                               minus the space occupied by the daemon console window.
1407
///                               Used to arrange the client window.
1408
/// * `aspect_ratio_adjustment` - The `aspect_ratio_adjustment` daemon configuration.
1409
///                               Used to arrange the client window.
1410
/// * `index_offset`            - Offset used to position the new windows correctly
1411
///                               from the start, avoiding flickering.
1412
///
1413
/// # Returns
1414
///
1415
/// A [`Clients`] collection preserving the launch order and indexed by
1416
/// process id for pipe-server correlation.
1417
0
async fn launch_clients<W: WindowsApi + 'static + Clone>(
1418
0
    windows_api: &W,
1419
0
    hosts: Vec<String>,
1420
0
    username: &Option<String>,
1421
0
    port: Option<u16>,
1422
0
    debug: bool,
1423
0
    workspace_area: &workspace::WorkspaceArea,
1424
0
    aspect_ratio_adjustment: f64,
1425
0
    index_offset: usize,
1426
0
) -> Clients {
1427
0
    let len_hosts = hosts.len();
1428
0
    let _guard = WindowsSettingsDefaultTerminalApplicationGuard::new();
1429
1430
    // Create an Arc to share the windows_api across parallel tasks
1431
0
    let windows_api_arc = Arc::new(windows_api.clone());
1432
1433
    // Create tasks for each client launch using spawn_blocking to handle the synchronous operations
1434
0
    let mut tasks = Vec::new();
1435
1436
0
    for (index, host) in hosts.into_iter().enumerate() {
1437
0
        let username_client = username.clone();
1438
0
        let workspace_area_client = *workspace_area;
1439
0
        let windows_api_clone = Arc::clone(&windows_api_arc);
1440
1441
        // Use spawn_blocking to run the synchronous launch_client_console in parallel
1442
0
        let task = tokio::task::spawn_blocking(move || {
1443
0
            let (window_handle, process_handle, process_id) = launch_client_console(
1444
0
                windows_api_clone.as_ref(),
1445
0
                &host,
1446
0
                username_client,
1447
0
                port,
1448
0
                debug,
1449
0
                index + index_offset,
1450
0
                &workspace_area_client,
1451
0
                len_hosts + index_offset,
1452
0
                aspect_ratio_adjustment,
1453
0
            );
1454
            // The receivers are dropped immediately; pipe-server tasks
1455
            // acquire their own receivers via `subscribe()` after PID
1456
            // correlation. Holding the senders on the [`Client`] keeps both
1457
            // channels alive for the lifetime of the client.
1458
0
            let (state_sender, _state_receiver) = watch::channel(ClientState::Active);
1459
0
            let (highlight_sender, _highlight_receiver) = watch::channel(false);
1460
0
            return (
1461
0
                index,
1462
0
                Client {
1463
0
                    hostname: host,
1464
0
                    window_handle,
1465
0
                    process_handle,
1466
0
                    process_id,
1467
0
                    state_sender,
1468
0
                    highlight_sender,
1469
0
                    // Placeholder - `Clients::push` overwrites with the
1470
0
                    // dense `list.len()`-based tile index.
1471
0
                    tile_index: 0,
1472
0
                },
1473
0
            );
1474
0
        });
1475
1476
0
        tasks.push(task);
1477
    }
1478
1479
    // Wait for all tasks to complete in parallel
1480
0
    let mut results = Vec::new();
1481
0
    for task in tasks {
1482
0
        match task.await {
1483
0
            Ok(result) => results.push(result),
1484
0
            Err(e) => panic!("Failed to launch client: {e}"),
1485
        }
1486
    }
1487
1488
    // Sort results by index to maintain order
1489
0
    results.sort_by_key(|(index, _)| return *index);
1490
1491
0
    let mut clients = Clients::new();
1492
0
    for (_, client) in results.into_iter() {
1493
0
        clients.push(client);
1494
0
    }
1495
0
    return clients;
1496
0
}
1497
1498
/// Build the argv for a spawned `client` console process.
1499
1
fn build_client_args(
1500
1
    host: &str,
1501
1
    username: Option<String>,
1502
1
    port: Option<u16>,
1503
1
    debug: bool,
1504
1
    daemon_channel: &str,
1505
1
) -> Vec<String> {
1506
1
    let mut client_args: Vec<String> = Vec::new();
1507
1
    if debug {
1508
1
        client_args.push("-d".to_string());
1509
1
    
}0
1510
1
    let mut actual_host = host;
1511
1
    let mut actual_username = username;
1512
1
    if let Some(split_result) = host.split_once("@") {
1513
1
        actual_username = Some(split_result.0.to_owned());
1514
1
        actual_host = split_result.1;
1515
1
    
}0
1516
1
    if let Some(actual_username) = actual_username.as_deref() {
1517
1
        client_args.extend(vec!["-u".to_string(), actual_username.to_string()]);
1518
1
    
}0
1519
1
    if let Some(port) = port {
1520
1
        client_args.extend(vec!["-p".to_string(), port.to_string()]);
1521
1
    
}0
1522
1
    client_args.push("client".to_string());
1523
1
    client_args.extend(vec![
1524
1
        "--daemon-channel".to_string(),
1525
1
        daemon_channel.to_string(),
1526
    ]);
1527
    // `--` keeps a host starting with `-` positional.
1528
1
    client_args.extend(vec!["--".to_string(), actual_host.to_string()]);
1529
1
    return client_args;
1530
1
}
1531
1532
/// Launchs a `client` console process with its own window with the given
1533
/// CLI arguments/options: `host`, `username`, `port`, `debug`.
1534
///
1535
/// Waits for the window to open, then re-arranges it based on
1536
/// the total number of clients, the size of the daemon console window and
1537
/// its index relative to the other client windows.
1538
///
1539
/// # Arguments
1540
///
1541
/// * `windows_api`             - The Windows API implementation to use
1542
/// * `host`                    - Hostname the client should connect to
1543
/// * `username`                - Username the client should use
1544
/// * `port`                    - Optional port for SSH connections
1545
/// * `debug`                   - Toggle debug mode on the client
1546
/// * `index`                   - The index of the client in the list of all clients.
1547
///                               Used to re-arrange the client window.
1548
/// * `workspace_area`          - The available workspace area on the primary monitor
1549
///                               minus the space occupied by the daemon console window.
1550
/// * `number_of_consoles`      - The total number of active client console windows.
1551
/// * `aspect_ratio_adjustment` - The `aspect_ratio_adjustment` daemon configuration.
1552
///
1553
/// # Returns
1554
///
1555
/// A tuple containing the window handle, process handle, and process id of the
1556
/// client process.
1557
0
fn launch_client_console<W: WindowsApi>(
1558
0
    windows_api: &W,
1559
0
    host: &str,
1560
0
    username: Option<String>,
1561
0
    port: Option<u16>,
1562
0
    debug: bool,
1563
0
    index: usize,
1564
0
    workspace_area: &workspace::WorkspaceArea,
1565
0
    number_of_consoles: usize,
1566
0
    aspect_ratio_adjustment: f64,
1567
0
) -> (HWND, HANDLE, u32) {
1568
0
    let daemon_channel = crate::utils::windows::control_endpoint(std::process::id());
1569
0
    let client_args = build_client_args(
1570
0
        host,
1571
0
        username,
1572
0
        port,
1573
0
        debug,
1574
0
        &daemon_channel.to_string_lossy(),
1575
    );
1576
1577
0
    let process_info = spawn_console_process(windows_api, &current_exe_path(), client_args, false)
1578
0
        .expect("Failed to create process");
1579
0
    let client_window_handle = get_console_window_handle(windows_api, process_info.dwProcessId);
1580
0
    let process_handle = windows_api
1581
0
        .open_process(PROCESS_QUERY_INFORMATION.0, false, process_info.dwProcessId)
1582
0
        .unwrap_or_else(|err| {
1583
0
            panic!(
1584
                "Failed to open process handle for process {}: {}",
1585
                process_info.dwProcessId, err
1586
            );
1587
        });
1588
1589
0
    arrange_client_window(
1590
0
        windows_api,
1591
0
        &client_window_handle,
1592
0
        workspace_area,
1593
0
        index,
1594
0
        number_of_consoles,
1595
0
        aspect_ratio_adjustment,
1596
    );
1597
0
    return (
1598
0
        client_window_handle,
1599
0
        process_handle,
1600
0
        process_info.dwProcessId,
1601
0
    );
1602
0
}
1603
1604
/// Correlate the connecting client by the PID in its `Hello`, then multiplex
1605
/// keystrokes, [`ClientState`] updates, and keep-alives onto the named pipe.
1606
///
1607
/// The post-subscribe initial-state push is intentional: `state_receiver.changed`
1608
/// only fires on transitions observed *after* `subscribe`, so a state set
1609
/// in the brief window between [`Client`] construction and `subscribe`
1610
/// would otherwise leave the client on its default until the next
1611
/// transition.
1612
///
1613
/// The `select!` is biased toward `recv` so the keep-alive tick never
1614
/// preempts active input traffic; the [`ClientState::Disabled`] arm
1615
/// therefore probes the pipe itself, otherwise sustained input would
1616
/// hide a disconnect.
1617
///
1618
/// # Errors and termination
1619
///
1620
/// An unknown PID exits the process (production) or panics (tests) -
1621
/// the daemon's bookkeeping is broken and recovery is not possible.
1622
/// A failed pipe write or a dropped [`watch::Sender`] ends the routine
1623
/// cleanly.
1624
4
async fn named_pipe_server_routine(
1625
4
    mut server: WindowsControlChannelServer,
1626
4
    receiver: &mut Receiver<ClientBroadcast>,
1627
4
    clients: Arc<Mutex<Clients>>,
1628
4
) {
1629
    // wait for a client to connect
1630
4
    server.accept().await.unwrap_or_else(|err| 
{0
1631
0
        error!("{}", err);
1632
0
        panic!("Timed out waiting for clients to connect to named pipe server",)
1633
    });
1634
1635
4
    let Some(hello) = read_client_hello(&mut server).await else {
1636
0
        return;
1637
    };
1638
4
    if let Err(
mismatch0
) = check_version(DAEMON_PROTOCOL_VERSION, hello.protocol_version) {
1639
0
        error!(
1640
            "Protocol version mismatch: daemon {} vs client {}",
1641
            mismatch.local, mismatch.remote
1642
        );
1643
0
        return;
1644
4
    }
1645
4
    let max_frame_len = negotiate_max_frame_len(DEFAULT_MAX_FRAME_LEN, hello.max_frame_len);
1646
4
    let pid = hello.pid;
1647
1648
4
    let (
mut state_receiver3
,
mut highlight_receiver3
) = match clients.lock().unwrap().get_by_pid(pid)
1649
    {
1650
3
        Some(client) => (
1651
3
            client.state_sender.subscribe(),
1652
3
            client.highlight_sender.subscribe(),
1653
3
        ),
1654
        None => {
1655
1
            error!(
1656
                "Named pipe server received unknown PID {} - daemon bookkeeping broken",
1657
                pid
1658
            );
1659
            // In production this exits the daemon; in tests process::exit would kill
1660
            // the test runner, so we panic instead so tokio::spawn can catch it.
1661
            #[cfg(not(test))]
1662
            std::process::exit(1);
1663
            #[cfg(test)]
1664
1
            panic!("Unknown client PID {} - daemon bookkeeping broken", pid);
1665
        }
1666
    };
1667
1668
3
    let daemon_hello = Hello {
1669
3
        protocol_version: DAEMON_PROTOCOL_VERSION,
1670
3
        role: Role::Daemon,
1671
3
        pid: std::process::id(),
1672
3
        capabilities: Vec::new(),
1673
3
        max_frame_len: DEFAULT_MAX_FRAME_LEN,
1674
3
    };
1675
3
    let welcome = Welcome {
1676
3
        client_id: u64::from(pid),
1677
3
        server_capabilities: Vec::new(),
1678
3
    };
1679
3
    if !send_message(&mut server, &daemon_hello, max_frame_len).await
1680
3
        || !send_message(&mut server, &welcome, max_frame_len).await
1681
    {
1682
0
        return;
1683
3
    }
1684
3
    let keep_alive = encode_frame(&DaemonToClient::KeepAlive, max_frame_len)
1685
3
        .expect("A keep-alive is smaller than the Hello already sent");
1686
1687
    // Initial state push - see fn docs.
1688
3
    let initial_state = *state_receiver.borrow_and_update();
1689
3
    if !send_message(
1690
3
        &mut server,
1691
3
        &DaemonToClient::StateChange {
1692
3
            state: to_run_state(initial_state),
1693
3
        },
1694
3
        max_frame_len,
1695
3
    )
1696
3
    .await
1697
    {
1698
0
        return;
1699
3
    }
1700
1701
    // Initial highlight push - same rationale as the state push above.
1702
3
    let initial_highlight = *highlight_receiver.borrow_and_update();
1703
3
    if !send_message(
1704
3
        &mut server,
1705
3
        &DaemonToClient::Highlight {
1706
3
            on: initial_highlight,
1707
3
        },
1708
3
        max_frame_len,
1709
3
    )
1710
3
    .await
1711
    {
1712
0
        return;
1713
3
    }
1714
1715
    loop {
1716
        // Independent watch channels: `state_receiver` and `highlight_receiver` are forwarded over the pipe in whichever order this `select!` happens to pick them up, not the order the daemon-side senders fired.
1717
9
        tokio::select! {
1718
            biased;
1719
9
            
recv_result6
= receiver.recv() => {
1720
5
                let broadcast = match 
recv_result1
{
1721
5
                    Ok(val) => val,
1722
1
                    Err(RecvError::Lagged(skipped)) => {
1723
                        // Slow consumers (typically disabled clients) drop
1724
                        // frames rather than kill the routine; debug-level
1725
                        // because this can fire repeatedly under load.
1726
1
                        debug!(
1727
                            "Named pipe server routine lagged behind broadcast channel - dropping {} frame(s)",
1728
                            skipped
1729
                        );
1730
                        // Probe and yield so sustained lag cannot starve
1731
                        // the keep-alive tick (the `select!` is `biased`
1732
                        // toward `recv`) and so a closed pipe is still
1733
                        // detected promptly under load.
1734
1
                        if !probe_pipe_alive(&server, &keep_alive) {
1735
0
                            return;
1736
1
                        }
1737
1
                        tokio::task::yield_now().await;
1738
1
                        continue;
1739
                    }
1740
                    Err(RecvError::Closed) => {
1741
0
                        error!("Broadcast channel closed");
1742
0
                        panic!("Failed to receive data from the Receiver");
1743
                    }
1744
                };
1745
5
                match broadcast {
1746
4
                    ClientBroadcast::Keystroke(frame) => {
1747
                        // Copy out before any `.await` - `watch::Ref` is not `Send`.
1748
4
                        let current_state = *state_receiver.borrow();
1749
4
                        match current_state {
1750
1
                            ClientState::Active => {}
1751
                            ClientState::Disabled => {
1752
                                // Probe the pipe so a disabled client cannot hide a
1753
                                // disconnect under sustained input - the keep-alive
1754
                                // tick is starved while recv keeps yielding frames.
1755
3
                                if !probe_pipe_alive(&server, &keep_alive) {
1756
0
                                    return;
1757
3
                                }
1758
3
                                tokio::task::yield_now().await;
1759
3
                                continue;
1760
                            }
1761
                        }
1762
1
                        if server.send(&frame).await.is_err() {
1763
0
                            return;
1764
1
                        }
1765
                    }
1766
1
                    ClientBroadcast::Terminate(frame) => {
1767
1
                        let _ = server.send(&frame).await;
1768
1
                        return;
1769
                    }
1770
                }
1771
            }
1772
9
            
changed_result1
= state_receiver.changed() => {
1773
                // Sender dropped - the daemon has removed this client from its
1774
                // bookkeeping, so there is nothing left to forward.
1775
1
                if changed_result.is_err() {
1776
0
                    debug!("Client state sender dropped, stopping named pipe server routine");
1777
0
                    return;
1778
1
                }
1779
1
                let state = *state_receiver.borrow_and_update();
1780
1
                if !send_message(
1781
1
                    &mut server,
1782
1
                    &DaemonToClient::StateChange { state: to_run_state(state) },
1783
1
                    max_frame_len,
1784
1
                )
1785
1
                .await
1786
                {
1787
0
                    return;
1788
1
                }
1789
            }
1790
9
            
changed_result0
= highlight_receiver.changed() => {
1791
                // Sender dropped - same rationale as the `state_receiver` arm.
1792
0
                if changed_result.is_err() {
1793
0
                    debug!("Client highlight sender dropped, stopping named pipe server routine");
1794
0
                    return;
1795
0
                }
1796
0
                let highlighted = *highlight_receiver.borrow_and_update();
1797
0
                if !send_message(
1798
0
                    &mut server,
1799
0
                    &DaemonToClient::Highlight { on: highlighted },
1800
0
                    max_frame_len,
1801
0
                )
1802
0
                .await
1803
                {
1804
0
                    return;
1805
0
                }
1806
            }
1807
9
            _ = tokio::time::sleep(Duration::from_millis(5)) => {
1808
1
                if server.send(&keep_alive).await.is_err() {
1809
1
                    return;
1810
0
                }
1811
            }
1812
        }
1813
    }
1814
2
}
1815
1816
/// Best-effort, non-blocking probe of the named pipe.
1817
///
1818
/// Returns `true` if the keep-alive frame either wrote successfully or
1819
/// returned `WouldBlock` (the pipe is still open but the OS buffer is
1820
/// full); `false` if any other error indicates the pipe is closed.
1821
4
fn probe_pipe_alive(server: &WindowsControlChannelServer, keep_alive: &[u8]) -> bool {
1822
4
    match server.try_write(keep_alive) {
1823
3
        Ok(_) => return true,
1824
1
        Err(e) if e.kind() == io::ErrorKind::WouldBlock => return true,
1825
        Err(_) => {
1826
0
            debug!("Named pipe server is closed, stopping named pipe server routine");
1827
0
            return false;
1828
        }
1829
    }
1830
4
}
1831
1832
/// Encode and send `message`, returning `false` once it cannot be delivered.
1833
13
async fn send_message<T: serde::Serialize>(
1834
13
    server: &mut WindowsControlChannelServer,
1835
13
    message: &T,
1836
13
    max_frame_len: u32,
1837
13
) -> bool {
1838
13
    match encode_frame(message, max_frame_len) {
1839
13
        Ok(frame) => return server.send(&frame).await.is_ok(),
1840
0
        Err(err) => {
1841
0
            error!("Failed to encode control frame: {}", err);
1842
0
            return false;
1843
        }
1844
    }
1845
13
}
1846
1847
/// Read the client's opening `Hello`, or `None` if it disconnects or sends anything else.
1848
4
async fn read_client_hello(server: &mut WindowsControlChannelServer) -> Option<Hello> {
1849
4
    let mut received = Vec::new();
1850
4
    let mut buffer = [0u8; 4096];
1851
    loop {
1852
4
        let count = server
1853
4
            .recv(&mut buffer)
1854
4
            .await
1855
4
            .ok()
1856
4
            .filter(|&count| return count > 0)
?0
;
1857
4
        received.extend_from_slice(&buffer[..count]);
1858
4
        let decoded = decode_frames::<Hello>(received, DEFAULT_MAX_FRAME_LEN).ok()
?0
;
1859
4
        if decoded.skipped > 0 || !decoded.messages.is_empty() {
1860
4
            return decoded.messages.into_iter().next();
1861
0
        }
1862
0
        received = decoded.remainder;
1863
    }
1864
4
}
1865
1866
/// Re-sizes and re-positions the given client window based on the total number of clients,
1867
/// the size of the daemon console window and its index relative to the other client windows.
1868
///
1869
/// # Arguments
1870
///
1871
/// * `windows_api`              - The Windows API implementation to use
1872
/// * `handle`                   - Reference the windows handle of a client console window.
1873
/// * `workspace_area`           - The available workspace area on the primary monitor
1874
///                                minus the space occupied by the daemon console window.
1875
/// * `index`                    - The index of the client in the list of all clients.
1876
/// * `number_of_consoles`       - The total number of active client console windows.
1877
/// * `aspect_ratio_adjustment` - The `aspect_ratio_adjustment` daemon configuration.
1878
0
fn arrange_client_window<W: WindowsApi>(
1879
0
    windows_api: &W,
1880
0
    handle: &HWND,
1881
0
    workspace_area: &workspace::WorkspaceArea,
1882
0
    index: usize,
1883
0
    number_of_consoles: usize,
1884
0
    aspect_ratio_adjustment: f64,
1885
0
) {
1886
0
    let (x, y, width, height) = determine_client_spatial_attributes(
1887
0
        index as i32,
1888
0
        number_of_consoles as i32,
1889
0
        workspace_area,
1890
0
        aspect_ratio_adjustment,
1891
0
    );
1892
    // Since windows update 10.0.19041.5072 it can happen that a client windows rendering is broken
1893
    // after a move+resize. Why is unclear, but resizing again does solve the issue.
1894
    // We first make the window 1 pixel in each dimension too small and imediately fix it.
1895
    // To reduce overhead we do not repaint the window the first time.
1896
0
    windows_api
1897
0
        .move_window(*handle, x, y, width - 1, height - 1, false)
1898
0
        .unwrap_or_else(|err| {
1899
0
            error!("{}", err);
1900
0
            panic!("Failed to move window",)
1901
        });
1902
0
    windows_api
1903
0
        .move_window(*handle, x, y, width, height, true)
1904
0
        .unwrap_or_else(|err| {
1905
0
            error!("{}", err);
1906
0
            panic!("Failed to move window",)
1907
        });
1908
0
}
1909
1910
/// Return the workspace area's aspect ratio (width / height) including
1911
/// the frame padding the tiler accounts for.
1912
///
1913
/// # Arguments
1914
///
1915
/// * `workspace_area` - Available workspace minus the daemon console.
1916
///
1917
/// # Returns
1918
///
1919
/// Aspect ratio as a `f64` for use by both the tiler and the navigation
1920
/// grid.
1921
3
fn workspace_aspect_ratio(workspace_area: &workspace::WorkspaceArea) -> f64 {
1922
3
    return (workspace_area.width + (workspace_area.x_fixed_frame + workspace_area.x_size_frame) * 2)
1923
3
        as f64
1924
3
        / (workspace_area.height + (workspace_area.y_fixed_frame + workspace_area.y_size_frame) * 2)
1925
3
            as f64;
1926
3
}
1927
1928
/// Calculates the position and dimensions for a client window given its index,
1929
/// the total number of clients and the `aspect_ratio_adjustment` daemon configuration.
1930
///
1931
/// # Arguments
1932
///
1933
/// * `index`                    - The index of the client in the list of all clients.
1934
/// * `number_of_consoles`       - The total number of active client console windows.
1935
/// * `workspace_area`           - The available workspace area on the primary monitor
1936
///                                minus the space occupied by the daemon console window.
1937
/// * `aspect_ratio_adjustment` - The `aspect_ratio_adjustment` daemon configuration.
1938
///     * `> 0.0` - Aims for vertical rectangle shape.
1939
///       The larger the value, the more exaggerated the "verticality".
1940
///       Eventually the windows will all be columns.
1941
///     * `= 0.0` - Aims for square shape.
1942
///     * `< 0.0` - Aims for horizontal rectangle shape.
1943
///       The smaller the value, the more exaggerated the "horizontality".
1944
///       Eventually the windows will all be rows.
1945
///       `-1.0` is the sweetspot for mostly preserving a 16:9 ratio.
1946
0
fn determine_client_spatial_attributes(
1947
0
    index: i32,
1948
0
    number_of_consoles: i32,
1949
0
    workspace_area: &workspace::WorkspaceArea,
1950
0
    aspect_ratio_adjustment: f64,
1951
0
) -> (i32, i32, i32, i32) {
1952
0
    let aspect_ratio = workspace_aspect_ratio(workspace_area);
1953
0
    let (grid_columns, grid_rows) =
1954
0
        grid_dimensions(number_of_consoles, aspect_ratio, aspect_ratio_adjustment);
1955
1956
0
    let grid_column_index = index % grid_columns;
1957
0
    let grid_row_index = index / grid_columns;
1958
1959
0
    let is_last_row = grid_row_index == grid_rows - 1;
1960
0
    let last_row_console_count = number_of_consoles % grid_columns;
1961
1962
0
    let console_width = if is_last_row && last_row_console_count != 0 {
1963
0
        (workspace_area.width / last_row_console_count)
1964
0
            + if last_row_console_count > 1 {
1965
0
                workspace_area.x_fixed_frame + workspace_area.x_size_frame
1966
            } else {
1967
0
                0
1968
            }
1969
    } else {
1970
0
        (workspace_area.width / grid_columns)
1971
0
            + (workspace_area.x_fixed_frame + workspace_area.x_size_frame)
1972
    };
1973
1974
0
    let console_height = (workspace_area.height
1975
0
        + (workspace_area.y_fixed_frame + workspace_area.y_size_frame) * grid_row_index)
1976
0
        / grid_rows;
1977
1978
0
    let x = grid_column_index * console_width
1979
0
        - ((workspace_area.x_fixed_frame + workspace_area.x_size_frame) * (grid_column_index + 1));
1980
0
    let y = grid_row_index * console_height
1981
0
        - ((workspace_area.y_fixed_frame + workspace_area.y_size_frame) * (grid_row_index - 1));
1982
1983
0
    return get_console_rect(x, y, console_width, console_height, workspace_area);
1984
0
}
1985
1986
/// Transform the position and dimensions of a console window based
1987
/// on the workspace area.
1988
///
1989
/// To minimize empty space between windows, width and height must be adjusted
1990
/// by the `fixed_frame` and `size_frame` values.
1991
///
1992
/// # Arguments
1993
///
1994
/// * `x`              - The `x` coordinate of the window.
1995
/// * `y`              - The `y` coordinate of the window.
1996
/// * `width`          - The `width` in pixels of the window.
1997
/// * `height`         - The `height` in pixels of the window.
1998
/// * `workspace_area` - The available workspace area on the primary monitor minus
1999
///                      the space occupied by the daemon console window.
2000
///
2001
/// # Returns
2002
///
2003
/// (`x`, `y`, `width`, `height`)
2004
///
2005
0
fn get_console_rect(
2006
0
    x: i32,
2007
0
    y: i32,
2008
0
    width: i32,
2009
0
    height: i32,
2010
0
    workspace_area: &workspace::WorkspaceArea,
2011
0
) -> (i32, i32, i32, i32) {
2012
0
    return (
2013
0
        std::cmp::max(
2014
0
            workspace_area.x - (workspace_area.x_fixed_frame + workspace_area.x_size_frame),
2015
0
            workspace_area.x - (workspace_area.x_fixed_frame + workspace_area.x_size_frame) + x,
2016
0
        ),
2017
0
        workspace_area.y - (workspace_area.y_fixed_frame + workspace_area.y_size_frame) + y,
2018
0
        std::cmp::min(workspace_area.width, width),
2019
0
        height,
2020
0
    );
2021
0
}
2022
2023
/// Spawns a background thread that ensures the z-order of all client
2024
/// windows is in sync with the daemon window.
2025
/// I.e. if the daemon window is focussed, all clients should be moved to the foreground.
2026
///
2027
/// # Arguments
2028
///
2029
/// * `windows_api` - Arc-wrapped Windows API implementation for thread-safe access
2030
/// * `clients`     - A thread safe mapping from the number
2031
///                   a client console window was launched at
2032
///                   in relation to the other client windows
2033
///                   and the clients console window handle.
2034
///                   The mapping must be thread safe to allow
2035
///                   it to be modified by the main thread
2036
///                   while we periodically read from it in the
2037
///                   background thread.
2038
0
fn ensure_client_z_order_in_sync_with_daemon<W: WindowsApi + Send + Sync + 'static>(
2039
0
    windows_api: Arc<W>,
2040
0
    clients: Arc<Mutex<Clients>>,
2041
0
) {
2042
0
    tokio::spawn(async move {
2043
0
        let daemon_handle = get_console_window_wrapper(windows_api.as_ref());
2044
0
        let mut previous_foreground_window = get_foreground_window_wrapper(windows_api.as_ref());
2045
        loop {
2046
0
            tokio::time::sleep(Duration::from_millis(1)).await;
2047
0
            let foreground_window = get_foreground_window_wrapper(windows_api.as_ref());
2048
0
            if previous_foreground_window == foreground_window {
2049
0
                continue;
2050
0
            }
2051
0
            if foreground_window == daemon_handle
2052
0
                && !clients.lock().unwrap().iter().any(|client| {
2053
0
                    return client.window_handle == previous_foreground_window.hwdn
2054
0
                        || client.window_handle == daemon_handle.hwdn;
2055
0
                })
2056
0
            {
2057
0
                defer_windows(
2058
0
                    windows_api.as_ref(),
2059
0
                    &clients.lock().unwrap(),
2060
0
                    &daemon_handle.hwdn,
2061
0
                );
2062
0
            }
2063
0
            previous_foreground_window = foreground_window;
2064
        }
2065
    });
2066
0
}
2067
2068
/// Move all given windows to the foreground.
2069
///
2070
/// Restores minimized windows.
2071
/// If a window handle no longer points to a valid window, it is skipped.
2072
/// The daemon window is deferred last and receives focus.
2073
///
2074
/// # Arguments
2075
///
2076
/// * `windows_api`                   - The Windows API implementation to use
2077
/// * `clients`                       - A thread safe mapping from the number
2078
///                                     a client console window was launched at
2079
///                                     in relation to the other client windows
2080
///                                     and the clients console window handle.
2081
/// * `daemon_handle`                 - Handle to the daemon console window.
2082
0
fn defer_windows<W: WindowsApi>(windows_api: &W, clients: &[Client], daemon_handle: &HWND) {
2083
0
    for client in clients.iter() {
2084
0
        restore_if_minimized(windows_api, client.window_handle, false);
2085
0
        let _ = windows_api.bring_window_to_top(client.window_handle, false);
2086
0
    }
2087
    // Raise the daemon last so it ends up on top and keeps keyboard focus.
2088
0
    restore_if_minimized(windows_api, *daemon_handle, true);
2089
0
    let _ = windows_api.bring_window_to_top(*daemon_handle, true);
2090
0
}
2091
2092
/// Restore `window_handle` if its current placement reports minimized.
2093
///
2094
/// Silently does nothing when the placement query fails or the window is
2095
/// not minimized. Used by [`defer_windows`] so both client and daemon
2096
/// windows are brought back from the taskbar before z-order updates.
2097
///
2098
/// # Arguments
2099
///
2100
/// * `windows_api`         - Windows API implementation.
2101
/// * `window_handle`       - Handle to the window to potentially restore.
2102
/// * `with_keyboard_focus` - Whether the restored window should be activated.
2103
///                           Pass `false` for client windows so unminimizing
2104
///                           them does not steal foreground from the daemon -
2105
///                           `SW_RESTORE` activates, which would let the
2106
///                           last-restored client win the foreground race and
2107
///                           block [`WindowsApi::bring_window_to_top`] from
2108
///                           refocusing the daemon.
2109
0
fn restore_if_minimized<W: WindowsApi>(
2110
0
    windows_api: &W,
2111
0
    window_handle: HWND,
2112
0
    with_keyboard_focus: bool,
2113
0
) {
2114
0
    let placement = match windows_api.get_window_placement(window_handle) {
2115
0
        Ok(placement) => placement,
2116
0
        Err(_) => return,
2117
    };
2118
0
    if placement.showCmd == SW_SHOWMINIMIZED.0.try_into().unwrap() {
2119
0
        let cmd = if with_keyboard_focus {
2120
0
            SW_RESTORE
2121
        } else {
2122
0
            SW_SHOWNOACTIVATE
2123
        };
2124
0
        let _ = windows_api.show_window(window_handle, cmd);
2125
0
    }
2126
0
}
2127
2128
/// The entrypoint for the `daemon` subcommand.
2129
///
2130
/// Spawns 1 client process with its own window for each host
2131
/// and 1 worker thread that handles communication with the client
2132
/// over a named pipe.
2133
/// Responsible for client window positioning and sizing.
2134
/// Handles control mode.
2135
/// Main thread reads input records from the console input buffer
2136
/// and propagates them via the background threads to all clients
2137
/// simultaneously.
2138
///
2139
/// # Arguments
2140
///
2141
/// * `windows_api` - The Windows API implementation to use
2142
/// * `hosts`    - List of hostnames for which to launch clients.
2143
/// * `username` - Username used to connect to the hosts.
2144
///                If none, each client will use the SSH config to determine
2145
///                a suitable username for their respective host.
2146
/// * `port`     - Optional port used for all SSH connections.
2147
/// * `config`   - The `DaemonConfig`.
2148
/// * `debug`    - Enables debug logging
2149
0
pub async fn main<W: WindowsApi + Clone + 'static>(
2150
0
    windows_api: &W,
2151
0
    hosts: Vec<String>,
2152
0
    username: Option<String>,
2153
0
    port: Option<u16>,
2154
0
    config: &DaemonConfig,
2155
0
    clusters: &[Cluster],
2156
0
    debug: bool,
2157
0
) {
2158
0
    let daemon: Daemon = Daemon {
2159
0
        hosts: explode(&hosts.join(" ")).unwrap_or(hosts),
2160
0
        username,
2161
0
        port,
2162
0
        config,
2163
0
        clusters,
2164
0
        control_mode_state: ControlModeState::Inactive,
2165
0
        debug,
2166
0
    };
2167
0
    daemon.launch(windows_api).await;
2168
0
    debug!("Actually exiting");
2169
0
}
2170
2171
#[cfg(test)]
2172
#[path = "../tests/daemon/test_mod.rs"]
2173
mod test_mod;